import { mallApi } from '/api/mall'
// import { taskApi } from '/api/task'
import { GlobalData } from '/store/state'
import { checkAuth } from '/store/actions'
import { $event, $logger, $utils } from '/utils'
import { getServer, checkUserisVip } from '/store/mutations'
import { userApi } from '/api/user'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    info: {} as DomoCommodity,

    commentFocus: false,
    inputValue: '',
    replyUser: 0,
    /** 键盘弹起高度 */
    keyboardOffsetTop: 0,

    loading: true,
    access: {},
    shareImage: '',
    share: false,
    interval: 4000,
    duration: 500,
    rechargeRatio: 0,
    /** 抵扣积分 */
    scoreNumber: 0,
    userScore: 0,
    scrollTop: false,
    follower: false,
    scrollClass: false,
    height: GlobalData.clientHeihgt - GlobalData.navigationHeight,
    navigationHeight: GlobalData.navigationHeight,
    currentTab: 0,
    navScrollLeft: 0,
    list: [] as DomoFeed[],
    noMore: false,
    collect: false,
    closable: false,
    query: {} as any,
    currencyName: GlobalData.currencyName,
    menuTop: 0,
    productInfo: {} as DomoCommodity,
    setTime: '' as any,
    num: 0,
    showpic: null as any,
    hidepic: null as any,
    mall_commodities: {} as DomoCommodity,
    mineId: 0,
    isAdmin: false,
    vip: GlobalData.vip,
    user: {} as DomoUser,
    /** 规格弹窗显示 */
    optionsShow: false,
    options: '',
    /** 加入购物车锁 */
    carts: false,
    showConfirm: false,
    orderId: 0,
    qrCodeShow: false,
    /** 是否有库存，默认有 */
    hasExtra: true,
    /** 选中的规格 */
    sku: {},
    skuIndex: 0,
    countPrice: 0,
    cartsCount: 0,
    previewType: 'image',
    swiperIndex: 0,
  },
  onLoad(query: any) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
    })
    let commodityId = +query.commodityId ? +query.commodityId : +query.id
    if (!commodityId && query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      commodityId = scene.commodityId ? +scene.commodityId : +scene.id
    }
    query.orderId &&
      this.setData({
        orderId: +query.orderId,
      })
    try {
      if (!commodityId) throw new Error('该商品不存在或已被删除')
      this.setData({
        loading: false,
      })
      this.getProductInfo(commodityId)
    } catch (error) {
      $logger.debug('商品详情加载失败', { query, error })
      wx.navigateBack({ delta: 1 })
      return
    }
    $event.on('after:boot', this, () => {
      this.getPostition()
    })
    $event.on('logged', this, () => {
      this.getUserId()
    })
    this.getPostition()
  },
  async onShow() {
    const token = wx.getStorageSync(`${getServer()}/accessToken`).data
    if (token) {
      wx.nextTick(() => {
        this.getUserId()
      })
    } else {
      await checkAuth()
    }
  },
  getPostition() {
    this.setData({
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      rechargeRatio: GlobalData.currency.settings['recharge-ratio'],
      vip: GlobalData.vip,
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      path: $utils.getSharePath(),
    }
  },
  onShareTimeline() {
    console.log($utils.getSharePath())

    return {
      title: this.data.info.title,
      imageUrl: this.data.info.photos[0].image.url,
      path: $utils.getSharePath(),
    }
  },
  onPageScroll() {
    this.fixedProductTitle()
  },
  /** 判断是否滚动到了商品名字 */
  fixedProductTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].top < 1 + this.data.navigationHeight : true,
      })
    })
  },
  onDownload() {
    $event.emit('download')
  },
  async onfollower() {
    await checkAuth()
    const mineId = this.getUserId()
    if (+mineId === +this.data.info.user_id) return
    //关注锁
    if (this.data.follower) return
    const userId = this.data.info.user_id
    this.setData({
      follower: true,
    })
    if (this.data.info.user.has_follower) {
      await userApi.unFollowUser(userId)
      this.setData({
        [`info.user.has_follower`]: false,
      })
      wx.showToast({ title: '已取消关注', icon: 'success' })
    } else {
      await userApi.followUser(userId)
      this.setData({
        [`info.user.has_follower`]: true,
      })
      wx.showToast({ title: '关注成功', icon: 'success' })
    }
    this.setData({
      follower: false,
    })
  },
  async getProductInfo(commodityId: any) {
    /** 有没有库存 */
    let {
      data: { hasExtra },
    } = this
    const productInfo = await mallApi.getCommodityDetail(commodityId, {
      width: 'shopInfo,snapshot',
    })
    const excludes = wx.getStorageSync(`${getServer()}/logged`).data
    const userScore = excludes ? excludes.currency.sum : 0
    /** 兼容之前发布的商品 */
    productInfo.type = productInfo.type == 'member' ? productInfo.type : 'score'
    /** 遍历商品规格库存 */
    if (productInfo.sku && productInfo.sku.length > 0) {
      hasExtra = productInfo.sku.some((i: any) => {
        return i.inventory > 0
      })
    }
    productInfo.userPrice = productInfo.market_price

    // 视频放第一位置。兼容旧数据
    for (let i = 0; i < productInfo.photos.length; i++) {
      if (productInfo.photos[i].video) {
        productInfo.photos = [productInfo.photos[i], ...productInfo.photos] as any
        productInfo.photos.splice(i + 1, 1)
        break
      }
    }

    this.setData({
      hasExtra,
      info: productInfo,
      productInfo,
      mall_commodities: productInfo,
      scoreNumber: productInfo.score > userScore ? userScore : productInfo.score,
      userScore,
      previewType:
        productInfo.photos.length >= 1 && productInfo.photos[0].video ? 'video' : 'image',
    })
  },
  async onLoadmore() {
    if (this.data.noMore) {
      wx.showToast({
        icon: 'none',
        title: '已没有更多',
      })
      return
    }
    wx.showLoading({ title: '加载中' })
    const offset = this.data.list.length
    const commodityId = this.data.info.id
    const list = await mallApi.getCommodityCommodities(commodityId, { offset, limit: 15 })
    const noMore = list.length < 15
    this.setData({
      list: [...this.data.list, ...list],
      noMore,
    })
    wx.hideLoading()
  },
  onReset() {
    /** 评论列表上划事件 */
  },
  /** 获取登录用户的ID */
  getUserId() {
    const abilities: any = GlobalData.userAbilities
    const isAdmin = abilities && abilities.some((i: any) => i.name === 'mall:admin')
    const user = wx.getStorageSync(`${getServer()}/logged`).data
    this.getCarts()
    if (user.vip) {
      user.vip.isVip = checkUserisVip(user)
    }
    this.setData({
      isAdmin,
      mineId: user.id,
      user,
    })
    return user.id
  },
  /** 购物车商品数量 */
  async getCarts() {
    const carts = await mallApi.getCartsCount()
    this.setData({
      cartsCount: carts.count,
    })
  },
  //开会员
  toVip() {
    wx.navigateTo({
      url: '/mine/vip/vip',
    })
  },
  toDetail() {
    const { info, orderId } = this.data
    wx.navigateTo({ url: `/mall/detail/detail?commodityId=${info.id}&orderId=${orderId}` })
  },
  /** 置顶操作 */
  swiperChange(e: any) {
    const { current } = e.detail
    this.setData({ swiperIndex: current })
  },
  switchPreview(e: any) {
    const { type } = e.currentTarget.dataset
    this.setData({ previewType: type })
  },
})
